const { chromium } = require("playwright");
const { v4: uuidv4 } = require("uuid");
const { post, get } = require("../../utils/request");

// 定义 sleep 函数
async function sleep(second) {
  return new Promise((resolve) => setTimeout(resolve, second * 1000));
}
const resUrl = {
  rzspss: [
    "/aweme/v1/web/discover/search/",
    "/aweme/v1/web/general/search/single/",
    "/aweme/v1/web/aweme/detail/",
    "/aweme/v1/web/aweme/post/",
  ],
  spplhq: ["/aweme/v1/web/comment/list/", "/aweme/v1/web/comment/list/reply/"],
  hqplrxx: ["/aweme/v1/web/user/profile/other/"],
};
async function onResonse(response, action, flowNo) {
  const myUrl = new URL(response.url());
  const path = myUrl.pathname;
  const filteredUrls = resUrl[action].filter((url) => url === path);
  if (filteredUrls.length > 0) {
    console.log(path);
    try {
      const text = await response.text();
      post(
        "http://electron-egg.local.com:42080/api/v1/crawler/dataSync/rawData/douyin",
        {
          url: myUrl,
          rawData: text,
          flowNo: flowNo,
        }
      )
        .then((res) => {
          console.log(res);
        })
        .catch((e) => {
          console.log("[child-process] onResonse error: ", e);
        });
    } catch (e) {
      console.log("[child-process] onResonse error: ", e);
    }
  }
}
async function mouseWheel(page, size) {
  const body = await page.waitForSelector("body");
  const bodySize = await page.evaluate(() => {
    const body = document.body;
    return {
      width: body.offsetWidth,
      height: body.offsetHeight,
    };
  });
  console.log("body 元素宽度:", bodySize.width);
  console.log("body 元素高度:", bodySize.height);
  // 移动鼠标到指定位置
  await page.mouse.move(bodySize.width / 2, bodySize.height / 2);
  await sleep(1);
  // 模拟向上滚动
  await page.mouse.wheel(0, bodySize.height / size);
}
async function rzspss(context, task) {
  console.log("[child-process] rzspss task: ", task);
  const cts = JSON.parse(task.context);
  const page = await context.newPage();
  page.on("response", async (response) => {
    await onResonse(response, "rzspss", task.flowNo);
  });
  const pageUrl = `https://www.douyin.com/root/search/${
    cts.keyword
  }?aid=${uuidv4()}&type=general`;
  console.log("[child-process] pageUrl: ", pageUrl);
  await page.goto(pageUrl, { timeout: 30000 });
  get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/zxz`);
  const slector = {
    pxyj: {
      综合排序: [1, 2],
      最新发布: [1, 3],
      最多点赞: [1, 4],
    },
    fbsj: {
      不限: [2, 2],
      一天内: [2, 3],
      一周内: [2, 4],
      半年内: [2, 5],
    },

    spsc: {
      不限: [3, 2],
      "1分钟以下": [3, 3],
      "1-5分钟": [3, 4],
      "5分钟以上": [3, 5],
    },
    ssfw: {
      不限: [4, 2],
      关注的人: [4, 3],
      最近看过: [4, 4],
      还未看过: [4, 5],
    },

    nrxs: {
      不限: [5, 2],
      视频: [5, 3],
      图文: [5, 4],
    },
  };
  let shaixuan;
  const array = ["pxyj", "fbsj", "spsc", "ssfw", "nrxs"];
  const start =
    "#search-content-area > div > div.eVQDrSwo > div.qWNh2IMg.CRPlkYAk.j7kc7ENz > div.ZyB0s4zV > div > div > div.jjU9T0dQ";
  for (let index = 0; index < array.length; index++) {
    const tag = array[index];
    const va = cts[tag];
    if (va == "不限" || va === "综合排序") {
      continue;
    }
    if (!shaixuan) {
      shaixuan = await page.waitForSelector(`${start} > span`, {
        timeout: 10000,
      });
      await shaixuan.hover();
    }
    const point = slector[tag][va];
    const item = await page.waitForSelector(
      `${start} > div > div:nth-child(${point[0]}) > span:nth-child(${point[1]})`,
      {
        timeout: 10000,
      }
    );
    item.click();
    await sleep(2);
  }
  let a = 0;
  do {
    a++;
    await mouseWheel(page, 2);
    const singleElementByCSS = await page.$(
      "#waterFallScrollContainer > div.nU717OFZ"
    );
    if (singleElementByCSS) {
      console.log("通过 CSS 选择器找到单个元素");
      break;
    }
  } while (a < 50);
  get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/ywc`);
}
async function spplhq(context, task) {
  let awemeList = await get(
    `http://electron-egg.local.com:42080/api/v1/aweme?flowNo=${task.flowNo}`
  );
  if (awemeList.length == 0) {
    get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/ywc`);
    return;
  }
  console.log("awemeList: ", awemeList);
  get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/zxz`);
  const page = await context.newPage();
  page.on("response", async (response) => {
    await onResonse(response, "spplhq", task.flowNo);
  });
  awemeList = ["7494145798670748937"];
  for (let index = 0; index < awemeList.length; index++) {
    const awemeId = awemeList[index];
    const pageUrl = `https://www.douyin.com/video/${awemeId}`;
    console.log("[child-process] pageUrl: ", pageUrl);
    await page.goto(pageUrl, { timeout: 30000, waitUntil: "domcontentloaded" });
    let a = 0;
    do {
      a++;
      await mouseWheel(page, 2);
      try {
        const singleElementByCSS = await page.waitForSelector(
          "#douyin-right-container > div.parent-route-container.route-scroll-container.h5AVrOfS > div > div > div.leftContainer.gkVJg5wr > div.KwRNeXA3 > div > div > div.HV3aiR5J.comment-mainContent > div.fanRMYie.cDj65BDb",
          { timeout: 100 }
        );
        break;
      } catch (e) {}
      const currentUrl = await page.url();
      console.log("当前页面的 URL 是:", currentUrl);
      if (currentUrl.includes("note")) {
        note(page);
        break;
      }
    } while (a < 50);
    get(`http://electron-egg.local.com:42080/api/v1/awemeMark/${awemeId}`);
    await sleep(5);
  }
  get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/ywc`);
}

async function note(page) {
  const element = await page.waitForSelector(
    "#detailrelatedVideoCard > div > div.oVW6Ln4S.JNsnEzRC.VwvTNAQg.t6DFrTdr > div > div.TclYH4Qn.rFPL_gS_",
    { timeout: 5000 }
  );
  await element.click();
  const pinlun = await page.waitForSelector(
    "#merge-all-comment-container > div > div.HV3aiR5J.comment-mainContent.iV2CcAAV",
    { timeout: 3000 }
  );
  const box = await pinlun.boundingBox();
  // 移动鼠标到指定位置
  await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
  let a = 0;
  do {
    a++;
    console.log("note");

    await sleep(1);
    // 模拟向上滚动
    await page.mouse.wheel(0, box.height / 2);
    try {
      const end = await page.waitForSelector(
        "#merge-all-comment-container > div > div.HV3aiR5J.comment-mainContent.iV2CcAAV > div.fanRMYie",
        { timeout: 300 }
      );
      break;
    } catch (error) {
      console.log("使用 waitForSelector 未找到元素");
    }
  } while (a < 50);
}

async function hqplrxx(context, task) {
  console.log("[child-process] hqplrxx task: ", task);
  const secUidList = await get(
    `http://electron-egg.local.com:42080/api/v1/secUid?flowNo=${task.flowNo}`
  );
  if (secUidList.length == 0) {
    get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/ywc`);
    return;
  }
  console.log("secUidList: ", secUidList);
  get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/zxz`);
  const pages = context.pages();
  const page = pages[pages.length - 1];
  page.on("response", async (response) => {
    await onResonse(response, "hqplrxx", task.flowNo);
  });
  for (let index = 0; index < secUidList.length; index++) {
    const secUid = secUidList[index];
    const pageUrl = `https://www.douyin.com/user/${secUid}`;
    console.log("[child-process] pageUrl: ", pageUrl);
    await page.goto(pageUrl, { timeout: 30000 });
    try {
      const element = await page.waitForSelector(
        "#user_detail_element > div > div.o1w0tvbC.F3jJ1P9_.InbPGkRv.W41XVmRl > div.SwoeMAEU.nWLhWdOv > div.ty_H89Vr > button.semi-button.semi-button-secondary.RH8TCnaE.z0c5Gipx.I4tJiW0Q > span",
        { timeout: 3000 }
      );
      console.log("使用 waitForSelector 找到元素");
      await element.click();
    } catch (error) {
      console.log("使用 waitForSelector 未找到元素");
    }
    get(`http://electron-egg.local.com:42080/api/v1/comment/${secUid}`);
    await sleep(5);
  }
}

async function fsslxx(context, task) {
  console.log("[child-process] fsslxx task: ", task);
  const secUidList = await get(
    `http://electron-egg.local.com:42080/api/v1/secUid?flowNo=${task.flowNo}`
  );
  if (secUidList.length == 0) {
    get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/ywc`);
    return;
  }
  console.log("secUidList: ", secUidList);
  get(`http://electron-egg.local.com:42080/api/v1/task/${task.id}/zxz`);
  const pages = context.pages();
  const page = pages[pages.length - 1];
  page.on("response", async (response) => {
    await onResonse(response, "hqplrxx", task.flowNo);
  });
  for (let index = 0; index < secUidList.length; index++) {
    const secUid = secUidList[index];
    const pageUrl = `https://www.douyin.com/user/${secUid}`;
    console.log("[child-process] pageUrl: ", pageUrl);
    await page.goto(pageUrl, { timeout: 30000 });
    try {
      const element = await page.waitForSelector(
        "#user_detail_element > div > div.o1w0tvbC.F3jJ1P9_.InbPGkRv.W41XVmRl > div.SwoeMAEU.nWLhWdOv > div.ty_H89Vr > button.semi-button.semi-button-secondary.RH8TCnaE.z0c5Gipx.I4tJiW0Q > span",
        { timeout: 3000 }
      );
      console.log("使用 waitForSelector 找到元素");
      await element.click();
    } catch (error) {
      console.log("使用 waitForSelector 未找到元素");
    }
    get(`http://electron-egg.local.com:42080/api/v1/comment/${secUid}`);
    await sleep(5);
  }
}
(async () => {
  const browser = await chromium.connectOverCDP(
    "ws://127.0.0.1:51560/devtools/browser/ded42fdd-add9-4f6c-8b18-be53e2bea1b3"
  );
  const context = browser.contexts()[0];
  const task = {
    id: 6,
    flowNo: "2e108789f26e472ea7bcafb7799d68c1",
    taskCode: "spplhq",
    context:
      '{"keyword":"JAVA","pxyj":"最新发布","fbsj":"一周内","spsc":"不限","ssfw":"不限","nrxs":"不限"}',
    priority: 22,
    status: "dzx",
    comment: "流程",
    createTime: 1744732581000,
  };
  //   await rzspss(context, task);
  await spplhq(context, task);
  // await hqplrxx(context, task);
})();
